﻿using AuthCenter.API.Read.Application.Commands.Accouns;
using AuthCenter.API.Read.DTO;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace AuthCenter.API.Read.Application.CommandHand.Accouns
{
    public class CascadeMenuCommandHand:IRequestHandler<CascadeMenuCommand,ApiResult<List<Cascaderitne>>>
    {
        public CascadeMenuCommandHand(IBaseRepository<MenuManageModel> menu,
            IBaseRepository<UserRoleModel> userrole,
            IBaseRepository<RoleMenuModel> rolepremiss)
        {
            Menu = menu;
            Userrole = userrole;
            Rolepremiss = rolepremiss;
        }

        public IBaseRepository<MenuManageModel> Menu { get; }
        public IBaseRepository<UserRoleModel> Userrole { get; }
        public IBaseRepository<RoleMenuModel> Rolepremiss { get; }

        public Task<ApiResult<List<Cascaderitne>>> Handle(CascadeMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<Cascaderitne>> result=new ApiResult<List<Cascaderitne>>();

            var list = GetCasxder(request);

            result.Code = ApiEnum.Success;
            result.Msg = "";
            result.Datas = list;
            return Task.FromResult(result);
        }

        public List<Cascaderitne> GetCasxder(CascadeMenuCommand command)
        {
            var cascaderitne = new List<Cascaderitne>();

            var permiss = new List<MenuManageModel>();

            if (command.UserId != 0)
            {
                var roleid = Userrole.GetAll().Where(x => x.Uid == command.UserId && !x.IsDeleted).Select(x => x.Rid).ToList();

                List<long> mode = new List<long>();

                foreach (var item in roleid)
                {
                    var menu = Rolepremiss.GetAll().Where(x => x.Rid == item && !x.IsDeleted).Select(x => Convert.ToInt64(x.Mid)).ToList();
                    mode.AddRange(menu);
                }

                permiss = Menu.GetAll().Where(x => x.Pid == command.ParentId && mode.Contains(x.Id) &&!x.IsDeleted).ToList();

            }
            else
            {
                permiss = Menu.GetAll().Where(x => x.Pid == command.ParentId && !x.IsDeleted).ToList();
            }

            foreach (var Item in permiss)
            {
                command.ParentId = Convert.ToInt32(Item.Id);
                cascaderitne.Add(new Cascaderitne()
                {
                    value=Item.Id,
                    label=Item.MenuName,
                    Path=Item.Url,
                    children = GetCasxder(command)
                });
            }
            return cascaderitne;
        }
    }
}
